from flask import Blueprint, render_template, request, jsonify
from .models import db, User
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.exceptions import HTTPException

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def home():
    return render_template('index.html')

@main_bp.route('/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        # 输入验证
        if not username or not password:
            return jsonify(message="Username and password are required"), 400
        if len(password) < 8:
            return jsonify(message="Password must be at least 8 characters long"), 400

        # 检查用户是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify(message="User already exists"), 400

        # 使用更安全的哈希算法
        hashed_password = generate_password_hash(password, rounds=12).decode('utf-8')
        new_user = User(username=username, password=hashed_password)
        db.session.add(new_user)
        db.session.commit()
        return jsonify(message="User registered successfully"), 201

    except Exception as e:
        db.session.rollback()
        return jsonify(message="An error occurred", error=str(e)), 500

@main_bp.route('/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        # 输入验证
        if not username or not password:
            return jsonify(message="Username and password are required"), 400

        user = User.query.filter_by(username=username).first()
        if user and check_password_hash(user.password, password):
            login_user(user)
            return jsonify(message="Login successful"), 200
        else:
            return jsonify(message="Invalid username or password"), 401

    except Exception as e:
        return jsonify(message="An error occurred", error=str(e)), 500

# 添加全局异常处理
@main_bp.errorhandler(Exception)
def handle_exception(e):
    if isinstance(e, HTTPException):
        return jsonify(message=e.description), e.code
    return jsonify(message="An internal error occurred"), 500